﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.WebProvider;
using System.Transactions;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class ProductModelsController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(ProductModelsModel model)
        {
            var total = 0;
            var list = ServiceFactory.ProductModelsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                BrandName = o.ProductBrands != null ? o.ProductBrands.BrandName : string.Empty,
                o.ID,
                o.ModelName,
                o.CreateBy,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.ImgUrl,
                o.Remark,
                ScreenTypeName = EnumHelper.Instance.GetDescription(typeof(ScreenTypeEnum), o.ScreenType),
                o.IsAvailable,
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.LastModifyBy,
                o.Sort,
                o.ModelCode
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit(int id)
        {
            var productModels = ServiceFactory.ProductModelsServiceInstance.LoadByID(id);
            return View(productModels);
        }

        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveProductModel(ProductModels model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            var serv = ServiceFactory.ProductModelsServiceInstance;

            var imageUrlFile = Request.Files["ImgUrl"];
            var imageUrlPath = FileHelper.UploadFile(imageUrlFile, Server);

            if (model.ID <= 0)
            {
                if (serv.IsExist(model.BrandId, model.ModelName))
                {
                    responseResult.Message = "该型号已经存在";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("Edit", new { id = model.ID });
                }
                model.CreateTime = DateTime.Now;
                model.CreateBy = CurrentUser.UserAccount;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;
                model.ImgUrl = string.IsNullOrWhiteSpace(imageUrlPath) ? model.ImgUrl : imageUrlPath;
                using (TransactionScope ts = new TransactionScope())
                {
                    var entity = serv.AddEntities(model);
                    responseResult.Success = entity.ID > 0;
                    //设置编码
                    if (!responseResult.Success)
                    {
                        ts.Dispose();
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("Edit", new { id = model.ID });
                    }
                    entity.ModelCode = CommonMethod.GenerateCode("XH", entity.ID.ToString(), 6);
                    if (!serv.UpdateEntities(entity))
                    {
                        ts.Dispose();
                        responseResult.Message = "操作失败！设置型号编码失败";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
                    }
                    ts.Complete();
                }
            }
            else
            {
                var entity = serv.LoadByID(model.ID);

                if (entity != null)
                {
                    if (model.ModelName != entity.ModelName && serv.IsExist(model.BrandId, model.ModelName, model.ID))
                    {
                        responseResult.Message = "已存在同名的型号，请修改型号名.";
                    }
                    else
                    {
                        //entity = ReflectHelper<ProductModels, ProductModels>.CloneT1ToT2(model, entity);
                        if (!string.IsNullOrWhiteSpace(imageUrlPath))
                        {
                            entity.ImgUrl = imageUrlPath;
                        }
                        entity.ScreenType = model.ScreenType;
                        entity.ModelName = model.ModelName;
                        entity.BrandId = model.BrandId;
                        entity.Sort = model.Sort;
                        entity.IsAvailable = model.IsAvailable;
                        entity.Remark = model.Remark;
                        entity.LastModifyBy = CurrentUser.UserAccount;
                        entity.LastModifyTime = DateTime.Now;
                        responseResult.Success = ServiceFactory.ProductModelsServiceInstance.UpdateEntities(entity);
                    }
                }
                else
                {
                    responseResult.Message = "该型号不存在或已被删除";
                    return RedirectToAction("Index");
                }
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("Index") : RedirectToAction("Edit", new { id = model.ID });
        }

        /// <summary>
        /// 启用或禁用型号
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isAvailable"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.ProductModelsServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.ProductModelsServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }

        #region 获取设备型号 + JsonResult GetProductModels(int productBrandsId)
        [HttpPost]
        public JsonResult GetProductModels(ProductModelSelectModel model)
        {
            //需要排除掉的设备信号ID列表
            List<long> ids = new List<long>();
            if (!string.IsNullOrEmpty(model.Ids))
                ids = model.Ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int64.Parse).ToList();

            var expressionWhere = PredicateExtensions.True<ProductModels>();
            expressionWhere = expressionWhere.And(o => o.IsAvailable == true);
            if (model.ProductTypeId > 0)
                expressionWhere = expressionWhere.And(o => o.ProductBrands.ProductTypeId == model.ProductTypeId);
            if (model.ProductBrandsId > 0)
                expressionWhere = expressionWhere.And(o => o.BrandId == model.ProductBrandsId);
            if (ids.Count > 0)
                expressionWhere = expressionWhere.And(o => !ids.Contains(o.ID));

            var entities = ServiceFactory.ProductModelsServiceInstance.LoadEntities(expressionWhere).Select(t => new
            {
                t.ID,
                t.ModelName
            }).AsNoTracking().OrderBy(t=>t.ModelName).ToList();
            return Json(new { Result = true, Data = entities });
        }
        #endregion
    }
}
